package com.trytech.mongoocrawler.server.transport.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;

/**
 * Created by coliza on 2017/7/31.
 */
public class HttpBody implements Serializable {
    private byte[] content;

    public byte[] getContent() {
        return content;
    }

    public void setContent(byte[] content) {
        this.content = content;
    }

    public JSON toJSON() {
        if(content != null && content.length>0){
            try {
                JSONObject jsonObj = JSONObject.parseObject(content, JSONObject.class);
                return jsonObj;
            }catch (Exception e){
                JSONArray jsonObj = JSONArray.parseArray(new String(content));
                return jsonObj;
            }
        }
        return null;
    }

    public static HttpBody parse(String s) throws UnsupportedEncodingException {
        HttpBody httpBody = new HttpBody();
        httpBody.setContent(s.getBytes(HttpProtocol.ENCODING));
        return httpBody;
    }

    public String getContentString(){
        return new String(content);
    }
}
